/**
 * 文档列表组件
 */

import React, { useEffect, useCallback, useState, useMemo } from 'react';
import { FileText } from 'lucide-react';
import { useDocument } from '@/contexts/document';
import { showMessage } from '@/components/common/MessageTip';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';
import DocumentItem from './DocumentItem';
import type { PersonalDocument } from '@/types/document';

interface DocumentListProps {
  className?: string;
}

export default function DocumentList({ className = '' }: DocumentListProps) {
  const {
    documents,
    loading,
    filter,
    sort,
    selectedCategoryId,
    selection,
    pagination,
    fetchDocuments,
    selectDocument,
    selectDocuments,
    toggleSelectAll,
    toggleFavorite,
    togglePin,
    deleteDocument,
    updatePagination,
    showAllDocuments,
    showFavorites
  } = useDocument();

  // 加载文档列表
  const loadDocuments = useCallback(async () => {
    try {
      await fetchDocuments();
    } catch (error) {
      console.error('Failed to load documents:', error);
    }
  }, [fetchDocuments]);

  // 选择文档
  const handleSelectDocument = useCallback((id: string, selected: boolean) => {
    const newSelectedIds = selected
      ? [...selection.selectedIds, id]
      : selection.selectedIds.filter((selectedId: string) => selectedId !== id);
    
    selectDocuments(newSelectedIds);
  }, [selection.selectedIds, selectDocuments]);

  // 切换收藏状态
  const handleToggleFavorite = useCallback(async (id: string) => {
    try {
      await toggleFavorite(id);
      showMessage('success', '收藏状态已更新');
    } catch (error) {
      showMessage('error', '操作失败');
      console.error('Failed to toggle favorite:', error);
    }
  }, [toggleFavorite]);

  // 切换置顶状态
  const handleTogglePin = useCallback(async (id: string) => {
    try {
      await togglePin(id);
      showMessage('success', '置顶状态已更新');
    } catch (error) {
      showMessage('error', '操作失败');
      console.error('Failed to toggle pin:', error);
    }
  }, [togglePin]);

  // 查看文档详情
  const handleViewDocument = useCallback((document: PersonalDocument) => {
    selectDocument(document.id);
  }, [selectDocument]);

  // 全选/取消全选
  const handleSelectAll = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    toggleSelectAll(e.target.checked);
  }, [toggleSelectAll]);

  // 删除相关状态
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [documentToDelete, setDocumentToDelete] = useState<PersonalDocument | null>(null);

  // 处理删除文档
  const handleDeleteDocument = useCallback((documentId: string) => {
    const document = documents.find(doc => doc.id === documentId);
    if (document) {
      setDocumentToDelete(document);
      setShowDeleteConfirm(true);
    }
  }, [documents]);

  // 确认删除文档
  const handleConfirmDelete = useCallback(async () => {
    if (!documentToDelete) return;

    try {
      await deleteDocument(documentToDelete.id);
      showMessage('success', `文档 "${documentToDelete.title}" 已删除`);
      setShowDeleteConfirm(false);
      setDocumentToDelete(null);
    } catch (error) {
      showMessage('error', '删除文档失败');
      console.error('Failed to delete document:', error);
    }
  }, [documentToDelete, deleteDocument]);

  // 取消删除
  const handleCancelDelete = useCallback(() => {
    setShowDeleteConfirm(false);
    setDocumentToDelete(null);
  }, []);



  // 本地排序和过滤
  const filteredDocuments = useMemo(() => {
    if (!documents || documents.length === 0) return [];
    
    // 首先应用前端筛选条件
    let result = [...documents];
    
    // 收藏筛选
    if (showFavorites) {
      result = result.filter(doc => doc.is_favorite);
    } else if (showAllDocuments) {
      // 显示所有文档，不需要额外筛选
    }
    
    // 本地排序
    result.sort((a, b) => {
      switch (sort.sortBy) {
        case 'title':
          return sort.sortOrder === 'asc' 
            ? a.title.localeCompare(b.title)
            : b.title.localeCompare(a.title);
        case 'file_size':
          return sort.sortOrder === 'asc'
            ? a.file_size - b.file_size
            : b.file_size - a.file_size;
        case 'created_at':
          return sort.sortOrder === 'asc'
            ? new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
            : new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        default:
          return 0;
      }
    });
    
    return result;
  }, [documents, sort.sortBy, sort.sortOrder, showFavorites, showAllDocuments]);

  // 首次加载文档
  useEffect(() => {
    loadDocuments();
  }, [loadDocuments]);

  // 搜索和分页变化时重新获取文档
  useEffect(() => {
    // 只有在搜索条件或分页条件变化时才重新获取文档
    // 排序条件变化时不重新获取，因为已经在前端进行了排序
    if (filter.search !== undefined || pagination.page !== undefined || pagination.size !== undefined) {
      loadDocuments();
    }
  }, [filter.search, pagination.page, pagination.size, loadDocuments]);

  // 加载中显示
  if (loading.documents) {
    return (
      <div className={`flex items-center justify-center py-12 ${className}`}>
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!filteredDocuments || filteredDocuments.length === 0) {
    return (
      <div className={`flex flex-col items-center justify-center py-12 ${className}`}>
        <FileText className="w-16 h-16 text-muted mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">
          {showFavorites ? '暂无收藏文档' : '暂无文档'}
        </h3>
        <p className="text-muted-foreground text-center">
          {showFavorites 
            ? '您还没有收藏任何文档'
            : filter.search || selectedCategoryId || filter.isFavorite || filter.isPinned
            ? '没有找到符合条件的文档'
            : '开始上传您的第一个文档吧'}
        </p>
      </div>
    );
  }

  return (
    <div className={`bg-card ${className}`}>
      {/* 列表头部 */}
      <div className="flex items-center px-4 py-2 bg-muted border-b border-border text-xs font-medium text-muted-foreground">
        <input
          type="checkbox"
          checked={selection.selectAll}
          onChange={handleSelectAll}
          className="w-4 h-4 text-primary border-input rounded focus:ring-ring mr-3"
        />
        <div className="w-8 mr-3"></div> {/* 文件图标占位 */}
        <div className="flex-1">文档名称</div>
        <div className="w-32 mr-4">标签</div>
        <div className="w-16 text-right mr-4">大小</div>
        <div className="w-20 text-right mr-4">创建时间</div>
        <div className="w-16"></div> {/* 操作按钮占位 */}
      </div>

      {/* 文档列表 */}
      <div>
        {(filteredDocuments || []).map((document: PersonalDocument) => (
          <DocumentItem
            key={document.id}
            document={document}
            isSelected={selection.selectedIds.includes(document.id)}
            onSelect={handleSelectDocument}
            onToggleFavorite={handleToggleFavorite}
            onTogglePin={handleTogglePin}
            onDelete={handleDeleteDocument}
            onView={handleViewDocument}
          />
        ))}
      </div>

      {/* 分页 */}
      {pagination.total > pagination.size && (
        <div className="flex items-center justify-between px-4 py-3 border-t border-border">
          <div className="text-sm text-muted-foreground">
            显示 {(pagination.page - 1) * pagination.size + 1} - {Math.min(pagination.page * pagination.size, pagination.total)} 
            ，共 {pagination.total} 个文档
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => updatePagination({ page: Math.max(1, pagination.page - 1) })}
              disabled={pagination.page === 1}
              className="px-3 py-1 text-sm border border-input rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-accent text-foreground"
            >
              上一页
            </button>
            <button
              onClick={() => updatePagination({ page: pagination.page + 1 })}
              disabled={pagination.page >= pagination.total_pages}
              className="px-3 py-1 text-sm border border-input rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-accent text-foreground"
            >
              下一页
            </button>
          </div>
        </div>
      )}

      {/* 删除确认模态框 */}
      <DeleteConfirmModal
        isOpen={showDeleteConfirm}
        onClose={handleCancelDelete}
        onConfirm={handleConfirmDelete}
        itemName={documentToDelete?.title || ''}
        title="删除文档"
        message="您确定要删除以下文档吗？"
        dangerMessage="注意：此操作不可撤销，删除后文档将无法恢复。"
      />
    </div>
  );
}
